package service.impl;

import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import service.interf.IWxMember;

import common.impl.MD5Transform;
import common.wx.WxAuth;
import common.wx.WxAuth.WxUser;

import dao.interf.IUserDAO;
import dao.interf.IWxMemberDAO;
import dao.pojo.User;
import dao.pojo.WxMember;

public class WxMemberImpl extends BaseDataServiceImpl implements IWxMember {
	private IWxMemberDAO wxMemberDao;
	private IUserDAO userDao;

	public void setWxMemberDao(IWxMemberDAO wxMemberDao) {
		this.wxMemberDao = wxMemberDao;
	}

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public WxMember add(String code) throws Exception {
		if (StringUtils.isEmpty(code))
			return null;
		WxUser wxUser = WxAuth.getByCode(code);
		String openId = wxUser.getOpenId();
		if (null == openId)
			return null;
		if ("".equals(openId.trim()))
			return null;
		WxMember wxMember = null;
		List<WxMember> wxMemberL = wxMemberDao.findByPropertiesRule(
				new String[] { "openId" }, new Object[] { openId }, null, null,
				0, 1);
		if (null == wxMemberL || wxMemberL.isEmpty()) {
			List<User> userL = userDao.findByPropertiesRule(
					new String[] { "userName" }, new Object[] { openId }, null,
					null, 0, 1);
			User user = null;
			if (null == userL || userL.isEmpty()) {
				user = new User();
				user.setUserName(openId);
				user.setPassword(MD5Transform.EncoderByMd5(openId, "utf-8"));
				user.setEnabled((short) 1);
				userDao.save(user);
			} else {
				user = userL.get(0);
			}
			wxMember = new WxMember();
			wxMember.setOpenId(openId);
			wxMember.setIsAuth(wxUser.isAuth());
			wxMember.setNickName(wxUser.getNickName());
			wxMember.setHeadUrl(wxUser.getHeadUrl());
			wxMember.setUser(user);
			wxMember.setUserId(user.getUserId());
			wxMember.setRegTime(myDateHandle.getCurrentDTString());
			wxMemberDao.save(wxMember);
		} else {
			wxMember = wxMemberL.get(0);
			if (wxUser.isAuth())
				wxMember.setIsAuth(wxUser.isAuth());
			if (!StringUtils.isEmpty(wxUser.getNickName()))
				wxMember.setNickName(wxUser.getNickName());
			if (!StringUtils.isEmpty(wxUser.getHeadUrl()))
				wxMember.setHeadUrl(wxUser.getHeadUrl());
			wxMemberDao.update(wxMember);
		}
		return wxMember;
	}

	public String init_add_point(Long userId) throws Exception {
		JSONObject jo = new JSONObject();
		jo.put("userId", userId);
		return jo.toString();
	}

}
